var Snake = function () {
    this.mapElent = document.querySelector(".tt-map");
    this.btnStart = document.querySelector(".btn-start");
    this.btnPause = document.querySelector(".btn-pause");
    this.scoreElement = document.querySelector(".score span");
    
    this.row = 20;
    this.col = 20;
    this.space = 30;
    this.elements = [];
    this.snakeArray = [];
    this.foodX = 0;
    this.foodY = 0;
    this.direction = "right";
    this.x = 2;
    this.y = 0;
}

Snake.prototype.createMap = function () {
    for(var i = 0 ; i < this.row ; i++) {
        var ul = document.createElement("ul");
        ul.style["height"] = this.space + "px";
        var arr = [];
        for(var j = 0 ; j < this.col ; j ++) {
            var li = document.createElement("li");
            li.style["width"] = this.space + "px";
            li.style["height"] = this.space + "px";
            arr.push(li);
            ul.appendChild(li);
        }
        this.elements.push(arr);
        this.mapElent.appendChild(ul);
    }
}

Snake.prototype.createSnake = function () {
    for(var i = 0 ; i < 3 ; i ++) {
        this.elements[0][i].className = "snake";
        this.snakeArray.push(this.elements[0][i]);
    }
}

Snake.prototype.myRandom = function (min,max) {
    return Math.floor(Math.random()*(max-min)+min);
}

Snake.prototype.createFood = function () {
    this.foodX = this.myRandom(0 , this.col);
    this.foodY = this.myRandom(0 , this.row);

    if(this.elements[this.foodY][this.foodX].className =="snake") {
        this.createFood();
    }else {
        this.elements[this.foodY][this.foodX].className = "food";
    }
}

Snake.prototype.snakeMove = function () {
    if(this.direction == "right") {
        this.x +=1;
    }
    if(this.direction == "left") {
        this.x -=1;
    }
    if(this.direction == "bottom") {
        this.y +=1;
    }
    if(this.direction == "top") {
        this.y -=1;
    }
    if(this.x == this.foodX && this.y == this.foodY) {

    }else {
        this.snakeArray[0].className = "";
        this.snakeArray.shift();
        this.elements[this.y][this.x].className = "snake";
        this.snakeArray.push(this.elements[this.y][this.x]);
    }
}

Snake.prototype.addEvent = function () {
    var _this = this;
    this.btnStart.onclick = function () {
        _this.snakeMove();
    }
}

Snake.prototype.init = function () {
    this.createMap();
    this.createSnake();
    this.createFood();
    this.addEvent();
}